package com.example.springbootexamples.controller;

import com.alibaba.fastjson.JSON;
import org.apache.commons.collections.MapUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;

@RestController
public class QpsController {

    Map<Long, AtomicInteger> map=new HashMap();

    @RequestMapping(value = "qps")
    public String qps(String s){
        Date date=new Date();
        /*SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        simpleDateFormat.*/
        String ss=date.getTime()+"";
        Long l=Long.parseLong(ss.substring(0,ss.length()-3)+"000");
        AtomicInteger a=map.get(l);
        if(a==null){
            a=new AtomicInteger(0);
            map.put(l,a);
        }
        a.addAndGet(1);
        return "aa";
    }

    @RequestMapping("qpsList")
    public String qpsList(){
        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        List<Map<String,Object>> list=new ArrayList<>();
        for(Long l:map.keySet()){
            String time=simpleDateFormat.format(new Date(l));
            Integer n=map.get(l).get();
            Map<String,Object> o=new HashMap<>();
            o.put("l",l);
            o.put("time",time);
            o.put("n",n);
            list.add(o);
        }
        list.sort(new Comparator<Map<String, Object>>() {
            @Override
            public int compare(Map<String, Object> o1, Map<String, Object> o2) {
                Long l1= MapUtils.getLong(o1,"l");
                Long l2= MapUtils.getLong(o2,"l");
                if(l1<l2){
                    return -1;
                }else if(l1>l2){
                    return 1;
                }
                return 0;
            }
        });
        String v= JSON.toJSONString(list);
        System.out.println(v);
        return v;
    }

    @RequestMapping("qpsClear")
    public String qpsClear(){
        map.clear();
        return "11";
    }


}
